<template>
    <div>
        <dl>
            <dt>
                <img :src="detail.avatar" alt="">
            </dt>
            <dd>
                <h2>{{detail.title}}</h2>
                <add-button :state="detail.state" :id="detail.id"></add-button>
            </dd>
        </dl>
    </div>
</template>
<script>
import addButton from '../components/add-button'
export default {
    components:{
        addButton
    },
    created(){
        this.getDetail();
        let shelfList = JSON.parse(localStorage.getItem('addList')) || [];
        this.$bus.$off('add');//避免重复添加事件
        this.$bus.$on('add',(state,id) => {
            this.detail.state = state;
            if(state){
                shelfList.push(this.detail)
            }else{
                let targetIndex = shelfList.findIndex(item => item.id === id);
                shelfList.splice(targetIndex,1);
            }
            localStorage.setItem('addList',JSON.stringify(shelfList));
        })
        
    },
    methods:{
        getDetail(){
            let shelfList = JSON.parse(localStorage.getItem('addList')) || [];
            this.$http.get('/api/detail',{params:{id:this.$route.params.id}}).then((res) => {
                if(res.data.code === 1){
                    let data = res.data.data;
                    data.state = false;
                    let target = shelfList.findIndex(item => item.id === data.id);
                    if(target != -1){
                        data.state = true;
                    }
                    this.detail = data;
                    console.log(this.detail)
                }
            }).catch((error) => {
                console.warn(error)
            })
        }
    },
    data(){
        return {
            detail:{}
        }
    }
}
</script>
